package org.example.utils

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
import io.searchbox.client.JestClient
import org.example.model.Point
import scalaj.http.{Http, HttpResponse}

import java.awt.geom.Point2D
import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer

/**
 * 经纬度相关工具类
 */
object MapUtils {
  /**
   * 将该省份下的所有县以上级别的电子围栏数据导入es,输入参数为该省份的adcode，详情请查看高德地图城市编码表 贵阳：520000 重庆：
   * @param provinceAdcode
   */
  def getElectronicFenceByProvinceAdcode(provinceAdcode:Int,provinceName:String): Unit ={
    val jestClient: JestClient = EsUtils.getClient()

    for (i <- provinceAdcode until provinceAdcode+10000){
      val jSONObject = getJson(i.toString)
      if (jSONObject != null){
        println(i)
        val features: JSONArray = jSONObject.getJSONArray("features")
        val featuresTheOne: JSONObject = features.getJSONObject(0)
        val properties = featuresTheOne.getJSONObject("properties")
        //区域编码
        val adcode = properties.getString("adcode")
        //区域名称
        var name = provinceName+properties.getString("name")
        println(name)
        val parent = properties.getJSONObject("parent")
        //上级区域编码
        val parent_adcode = parent.getString("adcode")

        val geometry = featuresTheOne.getJSONObject("geometry")
        val coordinatesJSONArray = geometry.getJSONArray("coordinates")
        val str = coordinatesJSONArray.getJSONArray(0).getJSONArray(0).toArray(Array[Object]())
        var listBuffer = new ListBuffer[(String)]()
        str.foreach(o=>{
          val s = o.toString
          val str1 = s.substring(1, s.length - 1)
          listBuffer.append(str1)
          str1
        })
        //区域经纬度
        val area_geom=listBuffer.toArray

        val is_del=0
        val is_use=1

        var center_point=properties.getJSONArray("center").getString(0)

        val electronicFence: ElectronicFence = ElectronicFence(
          adcode,
          name,
          parent_adcode,
          is_del,
          is_use,
          center_point,
          area_geom
        )
        var index ="electronic_fence_index"
        val typeStr: String = index.replace("index", "type")
        //将超速隐患证据写入es
        EsUtils.insertIntoEs(jestClient, index, typeStr, electronicFence)

      }
    }
    }

  /**
   * 根据adcode城市编码 获取电子围栏数据
   *
   * @param adcode
   * @return
   */
  def getJson(adcode:String): JSONObject = {
    try {
      val response: HttpResponse[String] = Http("http://geo.datav.aliyun.com/areas_v3/bound/"+adcode+".json").asString
      try {
        JSON.parseObject(response.body)
      } catch {
        case _ =>
          //println(s"JSON parse ERROR: ${response.body}")
          null
      }
    } catch {
      case _ =>
        null
    }
  }

  //车辆是否在区域内获取
  //lon:经度 lat:纬度 area：电子围栏
  def getVehicleIsInArea(lon: Double, lat: Double, area: List[Point2D.Double]): Boolean = {
    val pt = new Point2D.Double(lon, lat)
    Point.isInPolygon(pt, area.asJava)
  }

  //获取某一个站点的一个电子围栏
  def getArea(area_geom: Array[String]): List[Point2D.Double] = {
    val pts = area_geom.map { x =>
      val pt = x.split(",", -1)
      val ptd = try {
        // GCJ-02坐标系转WGS-84坐标系
        val locateInfo = TransformUtils.gcj02towgs84(pt(0).toDouble, pt(1).toDouble)
        (locateInfo._1, locateInfo._2)
      } catch {
        case e: Exception => (0.0, 0.0)
      }
      new Point2D.Double(ptd._1, ptd._2)
    }
    pts.toList
  }

}


case class ElectronicFence(var adcode: String,
                           var name: String,
                           var parent_adcode: String,
                           var is_del:Int,
                           var is_use:Int,
                           var center_point:String,
                           var area_geom: Array[String]
                          )
